﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Volo.Abp.Modularity;
using TianShu.WebApi;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class TianShuAspNetCoreServiceCollectionExtensions
    {

        public static IMvcBuilder AddTianShuControllers<T>(this IServiceCollection services)
        {

            return services.AddTianShuControllers<T>(opt => { });
        }
        public static IMvcBuilder AddTianShuControllers<T>(this IServiceCollection services, Action<MvcOptions> configure)
        {
            var mvcbuilder = services.AddControllers(configure);

            Dictionary<string, Assembly> addAssem = new Dictionary<string, Assembly>();

            GetApplicationPartAssem(addAssem, typeof(T));

            foreach (var item in addAssem)
            {
                mvcbuilder.AddApplicationPart(item.Value);
            }
            mvcbuilder.AddControllersAsServices();

            return mvcbuilder;
        }

        private static void GetApplicationPartAssem(Dictionary<string, Assembly> addAssem, Type type)
        {
            var depndsOnAttrs = type.GetCustomAttributes<DependsOnAttribute>();
            foreach (var attrItem in depndsOnAttrs)
            {
                foreach (var depItem in attrItem.DependedTypes)
                {
                    if (typeof(ITianShuApiModule).IsAssignableFrom(depItem) && addAssem.ContainsKey(depItem.FullName) == false)
                    {
                        addAssem[depItem.FullName] = depItem.Assembly;
                        GetApplicationPartAssem(addAssem, depItem);
                    }
                }
            }

        }
    }
}
